#include "stdio.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include "hdf_log.h"
#include "osal_mem.h"

#include "sht3x.h"
#include "sht3x_if.h"

#define HDF_LOG_TAG sht3x_app

int main(const int argc, char ** argv) 
{
    int ret;
    int times = 10;
    int mode = 1;
    uint8_t workmode;
    int32_t period = 1000;
    float temperature;
    float humidity;

    printf("Hello World.\r\n");

    int ch;  
    opterr = 0;  
    while ((ch = getopt(argc, argv, "M:T:P:")) != -1)  
    {
        switch(ch)  
        {  
            case 'M':
                printf("option M:'%s'\n", optarg);  
                mode = atoi(optarg);
                break;
            case 'T':
                printf("option T:'%s'\n", optarg); 
                times = atoi(optarg); 
                break;  
            case 'P':
                printf("option P:'%s'\n", optarg); 
                period = atoi(optarg); 
                break;  
            default:  
                printf("other option :%c\n",ch);  
        }  
    }  
    printf("optopt + %c\n",optopt);  

    switch(mode) {
        case 1: workmode = SHT3X_MODE_PERIOD_1HZ_H; break;
        case 2: workmode = SHT3X_MODE_POLL_M; break;
        case 3: workmode = SHT3X_MODE_CLK_STRETCH_H; break;
        case 4: workmode = SHT3X_MODE_PERIOD_2HZ_H; break;
        case 5: workmode = SHT3X_MODE_PERIOD_4HZ_H; break;
        default: return -1;
    }

    // 打开设备
    DevHandle sht3x = sht3xOpen(0);
    if (sht3x == NULL) {
        HDF_LOGE("[%s] %d.", __FUNCTION__, __LINE__);
        return -1;
    }

    // 设置模式
    ret = sht3xSetMode(sht3x, workmode);
    if (ret != HDF_SUCCESS) {
        HDF_LOGE("[%s] %d.", __FUNCTION__, __LINE__);

        // 关闭
        sht3xClose(sht3x);
        return -1;
    }

    // 非周期模式设置采样间隔
    if (mode == 2 || mode == 3)
        sht3xSetSamplingInterval(sht3x, 500);

    sht3xEnable(sht3x);

    while(times--)
    {
        usleep(period * 1000);

        sht3xGetTempData(sht3x, &temperature);
        sht3xGetHumiData(sht3x, &humidity);

        printf("temp : %f.\r\n", temperature);
        printf("humi : %f.\r\n", humidity);
    }

    // 失能
    sht3xDisable(sht3x);

    // 关闭
    sht3xClose(sht3x);

    return 0;
}
